package com.huijutao.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huijutao.MyApp;
import com.huijutao.NetUrl;
import com.huijutao.R;
import com.huijutao.adapter.HuihuiAdapter;
import com.huijutao.beans.Huihui;
import com.huijutao.callback.ABSFragment;
import com.huijutao.callback.StringDataCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;


public class HuiFragment extends ABSFragment implements AdapterView.OnItemClickListener, StringDataCallBack {

    private String max;
    private long last_time;
    private SimpleDateFormat sdf;
    private int r;
    public HuiFragment() {
    }

    private HuiFragmentCallBack mListener;
    private Huihui.ItemData itemdata;
    private ArrayList<Huihui.ItemData> datas;
    private HuihuiAdapter adapter;
    private PullToRefreshListView refreshListView;
    private String path = "http://app.huihui.cn/deals/channel.json";

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (HuiFragmentCallBack) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void setType(int r) {
        this.r=r;
        path=NetUrl.getHuiURL(r);
        datas.clear();
        MyApp.mStringUtils.getDataJson(path,this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_hui, container, false);
        refreshListView = (PullToRefreshListView) v.findViewById(R.id.huihui_list);
        ListView list = refreshListView.getRefreshableView();

        datas = new ArrayList<Huihui.ItemData>();
        Log.d("555", datas.size() + "fragment 1");
        MyApp.mStringUtils.getDataJson(path, this);
        Log.d("555", datas.size() + "fragment 2");
        adapter = new HuihuiAdapter(getActivity(), datas);
        list.setAdapter(adapter);
        /**
         * PullToRefreshListView
         */
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        final ILoadingLayout iLoadingLayout = refreshListView.getLoadingLayoutProxy();
        iLoadingLayout.setPullLabel("正在加载....");
        iLoadingLayout.setReleaseLabel("放开刷新");
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            private String mlast_time;

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                iLoadingLayout.setPullLabel("下拉刷新");
                String time = DateUtils.formatDateTime(getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL);
                iLoadingLayout.setLastUpdatedLabel(time);

                MyApp.mStringUtils.getDataJson(path, new StringDataCallBack() {
                    @Override
                    public void stringDataCallBack(String data) {
                        //重新下载
                        datas.clear();
                        huidown(data);

                    }
                });
                Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                iLoadingLayout.setPullLabel("上拉加载");
                String time = DateUtils.formatDateTime(getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL);
                iLoadingLayout.setLastUpdatedLabel(time);
                sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);

                mlast_time = datas.get(datas.size() - 1).getPub_time();
                try {
                    last_time = sdf.parse(mlast_time).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                max = "?with_merchant=1&max_time=" + last_time;
                MyApp.mStringUtils.getDataJson(path + max, new StringDataCallBack() {
                    @Override
                    public void stringDataCallBack(String data) {
                        huidown(data);
                    }
                });
            }
        });

        list.setOnItemClickListener(this);
        return v;
    }

    /**
     * 下载的数据，json解析
     *
     * @param data
     */
    @Override
    public void stringDataCallBack(String data) {
            huidown(data);
    }


    public void huidown(String data) {
        try {
            JSONObject jsob = new JSONObject(data);
            JSONArray jsonA = jsob.getJSONArray("data");
            for (int i = 0; i < jsonA.length(); i++) {
                JSONObject jsob2 = jsonA.getJSONObject(i);
                Huihui hui = new Huihui();
                itemdata = hui.new ItemData();
                itemdata.setTitle(jsob2.getString("title"));
                itemdata.setSub_title(jsob2.getString("sub_title"));
                itemdata.setId(jsob2.getInt("id"));
                String image_url = jsob2.getString("image_url");
                String image_new = image_url.replace("&quality=70&w=720", "&quality=70&w=170");
                itemdata.setImage_url(image_new);
                String time = jsob2.getString("pub_time");
                //time =Sun Apr 19 10:45:22 +0800 2015
                String[] times = time.split(" ");
                String t = times[0] + " " + times[1] + " " + times[2] + " " + times[3];
                itemdata.setEnd_time(t);
                itemdata.setPub_time(time);
                datas.add(itemdata);
                Log.d("555", datas.size() + "Huifragment");
            }
            adapter.notifyDataSetChanged();
            refreshListView.onRefreshComplete();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果是有分隔符的那种例如"a,b,c";就直接分割就行了.
     * String string = "a,b,c";
     * String [] stringArr= string.split(",");  //注意分隔符是需要转译滴...
     * 如果是"abc"这种字符串,就直接
     * String string = "abc" ;
     * char [] stringArr = string.toCharArray(); //注意返回值是char数组
     * 如果要返回byte数组就直接使用getBytes方法就ok了~~
     * String string = "abc" ;
     * byte [] stringArr = string.getBytes();
     */


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        itemdata = datas.get(position);
        String contentPath = "http://app.huihui.cn/deals/deal/" + itemdata.getId() + ".json?with_detail=1";
        mListener.HuiSendData(contentPath, itemdata.getTitle(), itemdata.getSub_title());
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * 回调接口
     * Created by Administrator on 2015/4/24.
     */
    public static interface HuiFragmentCallBack {

        public void HuiSendData(String data1, String data2, String data3);
    }
}